<template>
    <div class="update-password-container">
        <el-card class="password-card">
            <template #header>
                <div class="card-header">
                    <span>修改密码</span>
                </div>
            </template>
            <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="100px"
                class="password-form">
                <el-form-item label="原密码" prop="oldPassword">
                    <el-input v-model="passwordForm.oldPassword" type="password" show-password placeholder="请输入原密码" />
                </el-form-item>

                <el-form-item label="新密码" prop="newPassword">
                    <el-input v-model="passwordForm.newPassword" type="password" show-password placeholder="请输入新密码" />
                </el-form-item>

                <el-form-item label="确认密码" prop="rePassword">
                    <el-input v-model="passwordForm.rePassword" type="password" show-password placeholder="请再次输入新密码" />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="submitForm" :loading="loading">
                        提交
                    </el-button>
                    <el-button @click="resetForm">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage } from 'element-plus'
import { updatePassword } from '@/apis/userAPI'
import { useAuthStore } from '@/stores/auth/userAuthStore'
import { useRouter } from 'vue-router'

const router = useRouter()
const userStore = useAuthStore()
// 定义表单引用
const passwordFormRef = ref()

// 定义加载状态
const loading = ref(false)

// 定义表单数据
const passwordForm = reactive({
    oldPassword: '',
    newPassword: '',
    rePassword: ''
})

// 验证原密码
const validateOldPassword = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请输入原密码'))
    } else {
        callback()
    }
}

// 验证密码格式（包含字母和数字，长度6-20位）
const validatePasswordFormat = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请输入密码'))
    } else {
        const passwordRegex = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{6,20}$/
        if (!passwordRegex.test(value)) {
            callback(new Error('密码必须包含至少一个字母和一个数字，长度为6-20位'))
        } else {
            callback()
        }
    }
}

// 验证新密码与原密码不能相同
const validateDifferentPassword = (rule, value, callback) => {
    if (value === passwordForm.oldPassword) {
        callback(new Error('新密码不能与原密码相同'))
    } else {
        callback()
    }
}

// 验证确认密码与新密码相同
const validateConfirmPassword = (rule, value, callback) => {
    if (!value) {
        callback(new Error('请再次输入新密码'))
    } else if (value !== passwordForm.newPassword) {
        callback(new Error('两次输入的密码不一致'))
    } else {
        callback()
    }
}

// 定义表单验证规则
const passwordRules = {
    oldPassword: [
        { required: true, validator: validateOldPassword, trigger: 'blur' },
        { validator: validatePasswordFormat, trigger: 'blur' }
    ],
    newPassword: [
        { required: true, validator: validatePasswordFormat, trigger: 'blur' },
        { validator: validateDifferentPassword, trigger: 'blur' }
    ],
    rePassword: [
        { required: true, validator: validateConfirmPassword, trigger: 'blur' }
    ]
}

// 提交表单
const submitForm = () => {
    passwordFormRef.value.validate(async (valid) => {
        if (valid) {
            loading.value = true
            try {
                // 调用后端接口更新密码
                const result = await updatePassword(passwordForm)

                // 根据后端返回结果处理
                if (result.code === 1) {
                    ElMessage({
                        message: '密码修改成功,请重新登录！',
                        type: 'success'
                    })
                    resetForm()
                    userStore.logout()
                    // 跳转到首页
                    router.push('/')
                } else {
                    ElMessage({
                        message: response.message || '密码修改失败',
                        type: 'error'
                    })
                }
            } catch (error) {
                ElMessage({
                    message: error.message || '密码修改失败',
                    type: 'error'
                })
            } finally {
                loading.value = false
            }
        } else {
            console.log('表单验证失败')
            return false
        }
    })
}

// 重置表单
const resetForm = () => {
    passwordFormRef.value.resetFields()
}
</script>

<style scoped>
.update-password-container {
    padding: 20px;
    max-width: 500px;
    margin: 0 auto;
}

.card-header {
    font-size: 18px;
    font-weight: bold;
}

.password-form {
    margin-top: 20px;
}

.password-card {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
</style>